﻿using Microsoft.EntityFrameworkCore;

namespace cap01.Core.Db;

public static class EntityEx
{
    /// <summary>
    /// 在数据库中创建或更新对象
    /// </summary>
    public static void Upsert<T>(this DbContext db, T entity)
        where T : DbEntity
    {
        db.Upsert(entity.Id, entity, out _);
    }

    /// <summary>
    /// 在数据库中创建或更新对象
    /// </summary>
    public static void Upsert<T>(this DbContext db, object id, T entity, out T old)
        where T : class
    {
        var dbSet = db.Set<T>();

        old = dbSet.Find(id);

        if (old != null)
        {
            //更新
            db.Entry(old).State = EntityState.Detached;
            dbSet.Attach(entity);
            db.Entry(entity).State = EntityState.Modified;
        }
        else
        {
            dbSet.Attach(entity);
            db.Entry(entity).State = EntityState.Added;
        }
    }

    /// <summary>
    /// 标记删除
    /// </summary>
    public static void FlagAsDelete<T>(this DbSet<T> dbSet, Guid id)
        where T : DbEntity
    {
        var entity = dbSet.Find(id);
        if (entity is { IsDelete: false })
        {
            entity.IsDelete = true;
        }
    }


    /// <summary>
    /// 从数据库中物理删除
    /// </summary>
    public static void DeleteFromDB<T>(this DbSet<T> dbSet, Guid id)
        where T : DbEntity, new()
    {
        var entity = dbSet.Find(id);
        if (entity != null)
        {
            dbSet.Remove(entity);
        }
    }


    /// <summary>
    /// 根据Id查询对象
    /// </summary>
    public static T Get<T>(this DbSet<T> dbSet, Guid? id)
        where T : DbEntity
    {
        if (id == null)
            return null;

        return dbSet.Find(id);
    }


    /// <summary>
    /// 数据查询，不带删除的数据
    /// </summary>
    public static IQueryable<T> GetDbItems<T>(this DbSet<T> dbSet)
        where T : DbEntity
    {
        var items = dbSet.Where(i => !i.IsDelete);

        return items;
    }
}
